<!--
 * @author tanyuze
 -->
<template>
  <div v-loading="pageLoading" class="reveal-classify-pages">
    <div class="classify-btn">
      <div class="btn-title">
        <span>分类管理</span>
      </div>
      <div class="btn-btns">
        <el-button v-if="!allListIsEdit" @click="handleAddClassify">添加分类</el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      row-key="id"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      size="mini"
    >
      <el-table-column label="分类名称">
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-input
              v-model="scope.row.classifyName"
              class="edit-input"
              :class="[scope.row.parentId != -1 && 'children']"
              size="small"
              :maxlength="15"
            />
          </template>
          <template v-else>
            <span :class="[scope.row.parentId != -1 && 'children']">{{ scope.row.classifyName }}</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="标识" width="200">

        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-input
              v-model="scope.row.code"
              class="edit-input"
              :class="[scope.row.parentId != -1 && 'children']"
              size="small"
              :maxlength="15"
            />
            <el-button v-if="!allListIsEdit" class="addchild-btn" size="small" type="text" @click="addchild(scope.row)">
              添加子分类
            </el-button>
          </template>
          <template v-else>
            <span :class="[scope.row.parentId != -1 && 'children']">{{ scope.row.code }}</span>
            <el-button v-if="!allListIsEdit" class="addchild-btn" size="small" type="text" @click="addchild(scope.row)">
              添加子分类
            </el-button>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="200">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="ZT01"
            inactive-value="ZT02"
            @change="changeStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="移动" width="200">
        <template slot-scope="scope">
          <el-button :disabled="scope.row.isFirst" type="text" @click="move(scope.row, 'SY')">上移</el-button>
          <el-button :disabled="scope.row.isLast" type="text" @click="move(scope.row, 'XY')">下移</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-button type="text" style="color: #18a5fd; font-size: 14px" @click="handleSave(scope.row)">保存</el-button>
            <el-button type="text" style="color: #18a5fd; font-size: 14px" @click="handleCancel(scope.row)">取消
            </el-button>
          </template>
          <template v-else>
            <el-button type="text" style="color: #18a5fd; font-size: 14px" @click="handleUpdate(scope.row)">编辑
            </el-button>
          </template>
          <el-button type="text" style="color: #18a5fd; font-size: 14px" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { fetchList, del, insert, update, updateStatus, move } from './../api/category.js'
import permission from '@/directive/permission/index.js' // 权限判断指令
export default {
  name: 'RevealCategory',
  directives: { permission },
  filters: {
    formatStatus(val) {
      return val === 0 ? '启用' : val === 1 ? '禁用' : '禁用'
    },
    formatIshot(val) {
      return val === 0 ? '是' : val === 1 ? '否' : '否'
    }
  },
  data() {
    return {
      pageLoading: true,
      activeTab: 'FLLX_BQ',
      listLoading: false,
      searchshow: true,
      expandAll: true,
      list: [],
      curEditRow: {},
      allListIsEdit: false, // 分类树是否存在编辑情况，如果存在隐藏所有的添加下级按钮
      sortable: null,
      treeLevel: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    rowStyle({ row, columnIndex }) {
      if (columnIndex === 0) {
        return {
          textAlign: 'left'
        }
      } else if (columnIndex === 1) {
        return {
          display: 'flex'
        }
      } else {
        return {
          textAlign: 'center'
        }
      }
    },
    headerStyle({ row, columnIndex }) {
      if (columnIndex === 0) {
        return {
          textAlign: 'left'
        }
      } else {
        return {
          textAlign: 'center'
        }
      }
    },
    /**
     * 分类移动
     */
    move(row, dir) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return new Promise((resolve, reject) => {
        move({ id: row.id, msg: dir })
          .then(() => {
            this.$message({
              message: '处理成功',
              type: 'success',
              duration: 2000
            })
            loading.close()
            this.getList()
          })
          .catch((error) => {
            loading.close()
            this.getList()
            reject(error)
          })
      })
    },
    /**
     * 切换启用禁用状态
     */
    changeStatus(row) {
      if (!row.id) {
        return
      }
      if (!row.isEdit) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return new Promise((resolve, reject) => {
          updateStatus({ id: row.id, status: row.status })
            .then(() => {
              this.$message({
                message: '处理成功',
                type: 'success',
                duration: 2000
              })
              loading.close()
              this.getList()
            })
            .catch((error) => {
              loading.close()
              this.getList()
              reject(error)
            })
        })
      }
    },
    handleCancel(row) {
      if (row.id) {
        row['classifyName'] = this.curEditRow.classifyName
        row['status'] = this.curEditRow.status
        this.findPathByLeafId(row.id, this.list).isEdit = false
      } else {
        if (row.parentId) {
          this.findPathByLeafId(row.parentId, this.list).children.shift()
        } else {
          this.list.shift()
        }
      }
      this.allListIsEdit = false
    },
    handleUpdate(row) {
      if (this.allListIsEdit) {
        this.$message({
          message: '请先保存新添加分类',
          type: 'warning'
        })
        return
      } else {
        this.allListIsEdit = true
        this.curEditRow = Object.assign({}, row)
        this.findPathByLeafId(row.id, this.list).isEdit = true
      }
    },
    handleSave(row) {
      var obj = {
        id: row.id,
        classifyName: row.classifyName,
        code: row.code,
        bid: row.bid || '',
        status: row.status,
        parentId: row.parentId,
        classifyType: this.activeTab
      }
      this.save(obj)
    },
    save(obj) {
      if (!obj.classifyName) {
        this.$message({
          message: '请填写分类名称',
          type: 'warning'
        })
        return
      }
      if (!obj.code) {
        this.$message({
          message: '请填写分类标识',
          type: 'warning'
        })
        return
      }
      const pattern = new RegExp("^\\s|[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]|\\s$")
      if (pattern.test(obj.classifyName)) {
        this.$message({
          message: '请勿输入特殊字符或前后空格',
          type: 'warning'
        })
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (obj.id) {
        return new Promise((resolve, reject) => {
          update(obj)
            .then(() => {
              this.allListIsEdit = false
              this.$message({
                message: '处理成功',
                type: 'success',
                duration: 2000
              })
              loading.close()
              this.getList()
            })
            .catch((error) => {
              loading.close()
              reject(error)
            })
        })
      } else {
        return new Promise((resolve, reject) => {
          insert(obj)
            .then(() => {
              this.allListIsEdit = false
              this.$message({
                message: '处理成功',
                type: 'success',
                duration: 2000
              })
              loading.close()

              this.getList()
            })
            .catch((error) => {
              loading.close()
              reject(error)
            })
        })
      }
    },
    handleDel(row) {
      if (row.id) {
        this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.del(row.id)
          })
          .catch(() => {
          })
      } else {
        if (row.parentId) {
          this.findPathByLeafId(row.parentId, this.list).children.shift()
        } else {
          this.list.shift()
        }
        this.allListIsEdit = false
      }
    },
    del(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return new Promise((resolve, reject) => {
        del({ id: id })
          .then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    getList() {
      this.allListIsEdit = false
      this.listLoading = true
      return new Promise((resolve, reject) => {
        fetchList({ classifyType: this.activeTab })
          .then((response) => {
            this.listLoading = false
            this.list = this.initData(response.data.data)
            this.pageLoading = false
          })
          .catch((error) => {
            this.listLoading = false
            this.pageLoading = false
            reject(error)
          })
      })
    },
    /**
     * 递归增加是否可以上移下移标识
     * @param data
     * @returns {*}
     */
    initData(data, level = 1) {
      data.forEach((item, index) => {
        item['isFirst'] = false
        item['isLast'] = false
        item['isEdit'] = false
        if (index === 0) {
          item['isFirst'] = true
        }
        if (index === data.length - 1) {
          item['isLast'] = true
        }
        item['level'] = level
        if (item.children && item.children.length > 0) {
          return this.initData(item.children, level + 1)
        }
      })
      return data
    },
    addchild(row) {
      this.allListIsEdit = true
      row['_expanded'] = true
      /* let length = ''
      if (row.children) {
        length = row.children.length
      } else {

      }*/
      const obj = {
        id: '',
        classifyName: '',
        status: 'ZT01',
        isFirst: true,
        isLast: true,
        isEdit: true,
        parentId: row.id
      }
      this.findPathByLeafId(row.id, this.list).children.unshift(obj)
    },
    /**
     * 根据id递归查找所在的对象
     * @param data
     * @returns {*}
     */
    findPathByLeafId(leafId, nodes, path) {
      if (path === undefined) {
        path = {}
      }
      for (var i = 0; i < nodes.length; i++) {
        var tmpPath = path
        if (leafId === nodes[i].id) {
          tmpPath = nodes[i]
          return tmpPath
        }
        if (nodes[i].children) {
          var findResult = this.findPathByLeafId(leafId, nodes[i].children, tmpPath)
          if (findResult) {
            return findResult
          }
        }
      }
    },
    handleAddClassify() {
      this.allListIsEdit = true
      const list = this.list
      var length = list.length
      const obj = {
        id: '',
        parentId: '',
        classifyName: '',
        status: 'ZT01',
        isEdit: true,
        isFirst: true,
        isLast: true,
        index: length
      }
      list.unshift(obj)
      this.$set(this, 'list', list)
    },
    handleFilter() {
      this.getList()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
$dark_gray: #bfced6;
.reveal-classify-pages {
  padding: 20px;

  .classify-tab {
    width: 100%;
    margin-bottom: 10px;
    background-color: #fff;
    padding: 0 10px;

    .el-tabs__header {
      margin: 0;
    }
  }

  .classify-btn {
    display: flex;
    height: 46px;
    line-height: 46px;

    .btn-title {
      flex: 1;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }

  .el-table {
    background-color: transparent;

    thead {
      th {
        font-size: 14px;
        font-family: PingFangSC-Regular;
        font-weight: 400;
        color: rgba(166, 166, 166, 1);
      }
    }

    th,
    tr {
      background-color: transparent;
    }

    tbody {
      background-color: #ffffff;
      font-weight: 500;
    }
  }
}
</style>
<style scoped lang="scss">
.drag-handler {
  width: 20px;
  height: 20px;
  cursor: pointer;
  vertical-align: middle;
}

.edit-input {
  padding-right: 80px;

  &.children {
    padding-left: 20px;
  }
}

.addchild-btn {
  position: absolute;
  right: 15px;
  top: 6px;
}
</style>
